#include"fanDriver.hpp"
#include "../Global/globalDefs.hpp"
#include "../Global/globalVars.hpp"
#include <arduino.h>

#include "../tPumpShared/Preferences/Preferences.h"
#include "../tPumpShared/Misc/misc.hpp"

Preferences preferencesFan;

void setFanSpeedCore(int percentage) {
	int val = map(percentage, 0, 100, PWM0_OUTPUT_MIN, PWM0_OUTPUT_MAX);
	ledcWrite(FAN_PWM_CHNL, val);
}

int FanDriver::init(int percentage) {
	pinMode(FAN_PWM_PIN, OUTPUT);
	ledcSetup(DRIVE_PIN_0_PWM_CHNL, PWM0_Freq, PWM0_Res);
	ledcAttachPin(FAN_PWM_PIN, FAN_PWM_CHNL);
	Serial.print("To load fan speed. Default ");
	Serial.println(percentage);

	if (preferencesFan.begin("FAN", true)) {
		percentage = preferencesFan.getUChar("speed", percentage);
	}
	else {
		Serial.println("No config");
	}
	preferencesFan.end();

	Serial.print("Loaded ");
	Serial.println(percentage);

	setFanSpeedCore(percentage);
	return percentage;
}

int FanDriver::set(int percentage) {
	setFanSpeedCore(percentage);

	Serial.print("Set and save fan speed ");
	Serial.print(percentage);
	Serial.print("\r\n");
	Serial.flush();
	if (preferencesFan.begin("FAN", false)) {
		int size = preferencesFan.putUChar("speed", percentage);
		if (size != 1) {
			Serial.print("Unexpected size ");
			Serial.println(size);
		}
	}
	else {
		Serial.println("No config");
	}
	preferencesFan.end();

	return percentage;
}

void FanDriver::update(int percentage) {
	//return;
	setFanSpeedCore(percentage);
}
